<?php
namespace App\Api\User;

use PhalApi\Api;
use App\Domain\User\User as UserDomain;
use App\Domain\User\UserSession as UserSessionDomain;
use PhalApi\Exception\BadRequestException;


/**
 * 统计用户上级代理
 *
 */
class UserCount extends Api {
    public function getRules() {
        return array(
            'check' => array(),
        );
    }

    
    /**
     * 登录接口
     * @desc 根据账号和密码进行登录操作
     * @return array {
     *   success: boolean,
     *   data: {
     *     avatar: string,
     *     username: string,
     *     nickname: string,
     *     roles: string[],
     *     permissions: string[],
     *     accessToken: string,
     *     refreshToken: string,
     *     expires: string
     *   }
     * }
     */
    public function check() {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: *,x-token,X-token');

        function getInvitation($Invitation, &$invitations = []) {
            $user = \PhalApi\DI()
                        ->notorm->phalapi_user
                        ->where('username = ?', $Invitation)
                        ->fetchOne();
            if ($user) {
                $invitation = $user['Invitation'];
                if (!empty($invitation)) {
                    $invitations[] = $invitation;
                    getInvitation($invitation, $invitations);
                }
            }
            return $invitations;
        }

        $user = \PhalApi\DI()
                    ->notorm->phalapi_user
                    ->where('Invitations IS NULL')
                    ->order('id desc')
                    ->fetchOne();

        if (!$user) {
            \PhalApi\DI()->response->addResult('success', false);
            return [0, 0];
        }

        $Invitations = array();
        $initialInvitation = $user['Invitation'];
        $Invitations[] = $initialInvitation;

        $subInvitations = getInvitation($initialInvitation);
        $Invitations = array_merge($Invitations, $subInvitations);


        $update = \PhalApi\DI()
            ->notorm->phalapi_user
            ->where('id =?', $user['id'])
            ->update(array('Invitations' => implode(',', $Invitations)));
        \PhalApi\DI()->response->addResult('success', true);
        return [$user['id'], $update];

        
    }
    
    
}